package com.GLM.Viewer.Users;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.GLM.Constants.Constant;
import com.GLM.Entity.UserInfoDetailEntity;
import com.GLM.Tools.DB.DAO.UserInfoDAO;
import com.GLM.Tools.Utils.Image.AsynImageLoader;
import com.GLM.Tools.Utils.JSON.JSONResponse;
import com.GLM.Tools.Utils.JSON.JSONUtil;
import com.GLM.Tools.Utils.JSON.JSONResponse.Status;
import com.GLM.Viewer.R;
import com.GLM.Viewer.Friends.FriendsGroupsActivity;
import com.GLM.Viewer.Friends.FriendsSMSDetailActivity;
import com.google.gson.Gson;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class UserInfoDetailActivity extends Activity {
	private final static int USERINFO_LOADING = 111;
	private final static int USERINFO_LONDED = 222;
	Animation mAnimIn;
	Animation mAnimOut;
	
	View mInputFieldOneLine;
	TextView mInputFieldOneLineTextView;
	EditText mInputFieldOneLineEditText;
	InputMethodManager imm;
	
	private UserInfoDetailEntity userInfo = null;
	private ProgressBar mProgressBar;
	private Button followBtn;
	private Button fansBtn;
	private Button messageBtn;
	private Button GroupBtn;
	private Button sendSMSBtn;
	private Button remarkBtn;
	private Button careBtn;
	int userid ;
	private int myUserId;
	private boolean isFollowed;
	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Thread thread;
			switch (msg.what) {
			case USERINFO_LOADING:
				mProgressBar.setVisibility(View.VISIBLE);
				thread = new Thread(new Runnable() {
					public void run() {
					
						loadUserInfos();
						isFollowed = isFollows();
						mHandler.sendEmptyMessage(USERINFO_LONDED);
					}
				});
				thread.start();
				
				break;

			case USERINFO_LONDED:
				mProgressBar.setVisibility(View.GONE);
				initButtons();
				initViews();
				if(isFollowed){
					careBtn.setText(getString(R.string.unfollowing));
					sendSMSBtn.setVisibility(View.VISIBLE);
				}else{
					careBtn.setText(getString(R.string.following));
					sendSMSBtn.setVisibility(View.INVISIBLE);
				}
				
				
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_userinfo);
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		mProgressBar = (ProgressBar) findViewById(R.id.userinfo_progressbar);
		myUserId = UserInfoDAO.getUserInfo(UserInfoDetailActivity.this).getUserId();
		userid = getIntent().getIntExtra(Constant.INTENT_USER_ID, -1);
		if(myUserId == userid){
			GroupBtn.setVisibility(View.INVISIBLE);
			sendSMSBtn.setVisibility(View.INVISIBLE);
			remarkBtn.setVisibility(View.INVISIBLE);
			careBtn.setVisibility(View.INVISIBLE);
		}
		initInputFields();
		initAnimation();
		initRegisterInputFieldButton();
		mHandler.sendEmptyMessage(USERINFO_LOADING);
	}

	
	private void initInputFields() {
		mInputFieldOneLine = findViewById(R.id.inputfield_oneline);
		mInputFieldOneLine.setVisibility(View.GONE);
		mInputFieldOneLineTextView = (TextView) findViewById(R.id.inputfield_title);
		mInputFieldOneLineEditText = (EditText) findViewById(R.id.inputfield_edittext);

	}
	
	private void initAnimation() {
		mAnimIn = AnimationUtils.loadAnimation(this, R.anim.anim_register_in);
		mAnimOut = AnimationUtils.loadAnimation(this, R.anim.anim_register_out);
	}
	
	
	private void showOneLineInputField() {
		mInputFieldOneLine.startAnimation(mAnimIn);
		mInputFieldOneLine.setVisibility(View.VISIBLE);
		mInputFieldOneLineTextView.setText(getString(R.string.party_meetingplace_searchtips));
		mInputFieldOneLineEditText.requestFocus();
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
	}

	private void hideOneLineInputField() {
		mInputFieldOneLineEditText.setText("");
		mInputFieldOneLineEditText.setInputType(InputType.TYPE_NULL);
		mInputFieldOneLineEditText.clearFocus();
		mInputFieldOneLine.startAnimation(mAnimOut);
		mInputFieldOneLine.setVisibility(View.GONE);
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
		
	}
	
	private void initRegisterInputFieldButton() {
		// one line
		Button inputCancelButton = (Button) findViewById(R.id.inputfield_cancelbutton);
		inputCancelButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				hideOneLineInputField();
			}
		});

		Button inputOkButton = (Button) findViewById(R.id.inputfield_okbutton);
		inputOkButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				String remarkStr = mInputFieldOneLineEditText.getText().toString().trim();
				if(!remarkStr.equals("")){
					hideOneLineInputField();
					doRemarkUser(remarkStr);
				}
			}
		});
	}
	
	private void loadUserInfos() {
		
		JSONObject request = new JSONObject();
		try {
			request.put(Constant.PARAM_USERID, userid);
			JSONResponse jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_USERINFO, request);
			if (jsonResponse.getStatus() != Status.ERR) {
				JSONObject data = jsonResponse.getData();
				int status = -1;
				status = data.getInt(Constant.RESP_STATUS);
				if (status == Constant.RESP_STATUS_SUCCESS) {
					JSONObject jsonObject = data.getJSONObject(Constant.RESP_USERINFO_DETAIL);
					userInfo = new Gson().fromJson(jsonObject.toString(), UserInfoDetailEntity.class);
					
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	
	public void initButtons(){
		followBtn = (Button)findViewById(R.id.userInfo_follows);
		fansBtn = (Button)findViewById(R.id.userInfo_followed);
		messageBtn = (Button)findViewById(R.id.userInfo_message);
		followBtn.setOnClickListener(clickListener);
		fansBtn.setOnClickListener(clickListener);
		messageBtn.setOnClickListener(clickListener);
		GroupBtn = (Button)findViewById(R.id.userInfo_group);
		sendSMSBtn = (Button)findViewById(R.id.userInfo_sendsms);
		remarkBtn = (Button)findViewById(R.id.userInfo_rename);
		careBtn = (Button)findViewById(R.id.userInfo_unfollow);
		GroupBtn.setOnClickListener(clickListener);
		sendSMSBtn.setOnClickListener(clickListener);
		remarkBtn.setOnClickListener(clickListener);
		careBtn.setOnClickListener(clickListener);
	}
	
	public OnClickListener clickListener = new OnClickListener() {
		
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.userInfo_follows:
				Intent followsIntent = new Intent(UserInfoDetailActivity.this, UserFollowsActivity.class);
				followsIntent.putExtra("user_id", userInfo.getUser_id());
				startActivity(followsIntent);
				break;
			case R.id.userInfo_followed:
				Intent intent = new Intent(UserInfoDetailActivity.this,UserFansActivity.class);
				intent.putExtra("user_id", userInfo.getUser_id());
				startActivity(intent);
				break;
			case R.id.userInfo_message:
				Intent msgIntent = new Intent(UserInfoDetailActivity.this, UserMessageActivity.class);
				msgIntent.putExtra(Constant.INTENT_USER_ID, userInfo.getUser_id());
				startActivity(msgIntent);
				break;
			case R.id.userInfo_group:
				Intent groupIntent = new Intent(UserInfoDetailActivity.this,FriendsGroupsActivity.class);
				startActivity(groupIntent);
				break;
			case R.id.userInfo_sendsms:
				Intent sendsmsIntent = new Intent(UserInfoDetailActivity.this, FriendsSMSDetailActivity.class);
				sendsmsIntent.putExtra("talkId", userid);
				startActivity(sendsmsIntent);
				break;
			case R.id.userInfo_unfollow:
				doFollowUserorNotFollow();
				break;
			case R.id.userInfo_rename:
				mInputFieldOneLineTextView.setText(getString(R.string.rename));
				showOneLineInputField();
				break;
			default:
				break;
			}
		}
	};
	
	
	public void doRemarkUser(String remark){
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		
		try {
			
			jsonData.put(Constant.PARAM_USERID, myUserId);
			jsonData.put("rel_face_user_id", userid );
			jsonData.put("rel_relname", remark);
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_REMARKUSER, jsonData);
			if (jsonResponse.getStatus() != Status.ERR) {
				int status = -1;
				JSONObject data = jsonResponse.getData();
				status = data.getInt(Constant.RESP_STATUS);
				
			}
		} catch (Exception e) {
			// TODO: handle exception

		}
	}
	
	public void doFollowUserorNotFollow(){
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		int way = -1;
		try {
			if(isFollowed){
				way = 18;
			}else 
				way = 7;
			jsonData.put(Constant.PARAM_USERID, myUserId);
			jsonData.put("rel_face_user_id", userid );
			jsonResponse = JSONUtil.postRequest(way, jsonData);
			if (jsonResponse.getStatus() != Status.ERR) {
				int status = -1;
				JSONObject data = jsonResponse.getData();
				status = data.getInt(Constant.RESP_STATUS);
				if(status == 1){
					if(isFollowed){
						Toast.makeText(UserInfoDetailActivity.this, "取消关注成功", Toast.LENGTH_LONG).show();
					}else {
						Toast.makeText(UserInfoDetailActivity.this, "关注成功", Toast.LENGTH_LONG).show();
					}
					isFollowed = !isFollowed;
				}
			}
		} catch (Exception e) {
			// TODO: handle exception

		}
	}
	
	public boolean isFollows(){
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		try {
			jsonData.put(Constant.PARAM_CLASSID, userid );
			jsonData.put(Constant.PARAM_USERID_ONE, userid);
			jsonData.put(Constant.PARAM_FRIENDS_CLASS, 2);
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_GETFRIENDSSMS, jsonData);
			if (jsonResponse.getStatus() != Status.ERR) {
				int status = -1;
				JSONObject data = jsonResponse.getData();
				status = data.getInt(Constant.RESP_STATUS);
				if (status == Constant.RESP_STATUS_SUCCESS) {
					JSONArray jsonArray = data.getJSONArray(Constant.RESP_PARTY_USERS);

					Gson gson = new Gson();
					int i;
					for (i = 0; i < jsonArray.length(); i++) {
						UserInfoDetailEntity entity = gson.fromJson(jsonArray.getJSONObject(i).toString(), UserInfoDetailEntity.class);
						if(myUserId == entity.getUser_id()){
							return true;
						}
					}
					if(i == jsonArray.length())
						return false;
				}

			}
		} catch (Exception e) {
			// TODO: handle exception

		}
		return false;
	}
	
	private void initViews() {
		if (userInfo != null) {
			TextView nicknameView = (TextView) findViewById(R.id.userinfo_nickname);
			nicknameView.setText(userInfo.getUd_nickname());
			TextView locnameView = (TextView) findViewById(R.id.userinfo_locationname);
			locnameView.setText(userInfo.getLoc_name());
			// avatar
			ImageView avatarView = (ImageView) findViewById(R.id.userinfo_avatar);
			new AsynImageLoader().showImageAsyn(avatarView, Constant.URL_USER_MIDDLE + userInfo.getUser_avatar(), R.drawable.glm_white);
			Log.d("UserInfoDetail______", userInfo.getUser_avatar()+"");
			// buttons
			String str = getString(R.string.userinfo_detail_follows);
			followBtn.setText(str + userInfo.getFocus());
			str = getString(R.string.userinfo_detail_followed);
			fansBtn.setText(str + userInfo.getFollows());
			str = getString(R.string.userinfo_detail_messages);
			messageBtn.setText(str + userInfo.getMsg());
			// emotions
			String emotion = userInfo.getUd_breast();
			if (emotion != null && emotion.length() > 0) {
				TextView emotionView = (TextView) findViewById(R.id.userinfo_emotion);
				emotionView.setText(emotion);
			}
		} else {
			// TODO show error tips and go back;
		}

	}

	public void goBackButton_OnClick(View v) {
		finish();
	}
}
